package com.knowswift.issues.mqtt;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Data
@Configuration
@ConfigurationProperties("mqtt")
@Slf4j
public class MqttConfig {
    private Boolean enable;
    private String host;
    private String clientId;
    private String username;
    private String password;
    private Integer timeout;
    private Integer keepAlive;
    private List<String> topics;


    @Bean
    @ConditionalOnProperty(prefix = "mqtt", name = "enable", havingValue = "true")
    public MqttClient mqttClient(MqttMessageHandlerContext context) {
        try {
            MqttClient client = new MqttClient(host, clientId);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setCleanSession(true);
            options.setConnectionTimeout(timeout);
            options.setKeepAliveInterval(keepAlive);

            client.setCallback(new MessageCallback(client, context));
            IMqttToken iMqttToken = client.connectWithResult(options);
            boolean complete = iMqttToken.isComplete();
            log.info("mqtt建立连接：{}", complete);

            // 订阅主题
            for (String topic : topics) {
                IMqttToken response = client.subscribeWithResponse(topic, 0);
                log.info("订阅topic：{}", Arrays.toString(response.getTopics()));
            }
            return client;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("mqtt 连接异常");
            }
    }
}
